// 该文件本地测试用(方便测试小程序端请求)
/* eslint-disable @typescript-eslint/no-explicit-any */
import qs from "qs";
import { getToken, isUniMp } from "@ibiz-template/core";

type RequestOptions = UniApp.RequestOptions & {
  query?: Record<string, any>;
};

/**
 * UniApp请求拦截器
 */
const httpInterceptor = {
  invoke(options: RequestOptions): void {
    // 接口请求支持通过 query 参数配置 queryString
    if (options.query) {
      const queryStr = qs.stringify(options.query);
      if (options.url.includes("?")) {
        options.url += `&${queryStr}`;
      } else {
        options.url += `?${queryStr}`;
      }
    }
    // 请求超时
    options.timeout = 10000;
    // 请求头
    options.header = {
      platform: ibiz.env.mobPlatform,
      Authorization: `Bearer ${getToken()}`,
    };
    // 设置系统Id
    let systemId = ibiz.env.dcSystem;
    const { orgData } = ibiz;
    if (orgData) {
      if (orgData.systemid) {
        systemId = orgData.systemid;
      }
      if (orgData.orgid) {
        options.header.srforgid = orgData.orgid;
      }
    }
    options.header.srfsystemid = systemId;
    // 本地测试时将该前缀改为本地启动的h5端端口
    if (isUniMp()) {
      options.url = `http://172.19.220.93:5173` + options.url;
    }
  },
};

/**
 * 请求拦截器注册
 */
export const RequestInterceptor = {
  install(): void {
    // 拦截 request 请求
    uni.addInterceptor("request", httpInterceptor);
    // 拦截 uploadFile 文件上传
    uni.addInterceptor("uploadFile", httpInterceptor);
  },
};
